import Vue from 'vue'
import Router from 'vue-router'
import VueResource from 'vue-resource'

import { addDynamicRoutes } from './service'
import { getMenus } from './perimission'
import { getUserInfo } from '@/utils/storage.js'
import { getLoginInfo } from '@/api/login/index.js'
import { handleUserInfo } from '@/views/login/service'

Vue.use(Router)
Vue.use(VueResource)

// 解决导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push
// const originalReplace = Router.prototype.replace
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch((err) => err)
}
/* Router.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch((err) => err)
} */

/**
 * @desc 路由的自定义参数
 * @param { object } meta 元数据
 * @param { boolean } meta.menu  为true此路由作为菜单显示在左侧，默认false (控制一级菜单)
 * @param { string } meta.title 菜单显示的标题
 * @param { string } meta.c_icon 菜单显示的图标
 * @param { string } meta.c_class 菜单项添加自定义class
 * @param { boolean } meta.hidden 为true则隐藏当前菜单，默认false (控制子菜单，子菜单默认显示)
 * @param { boolean } meta.url 与后端约定的权限标识，根据此标识判断是否显示路由
 * a
 * @return { array } 创建的路由
 */
const createRoutes = () => [
  // 默认首页
  /* {
    path: '/',
  }, */
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/Login.vue'),
  },
  {
    path: '/Offcial/H5notFound',
    component: () => import('@/components/H5404'),
  },
]
const routes = createRoutes()

/* 默认页面， */
const PAGE_HOME = {
  path: '/',
  redirect: '',
}
const DEFAULT_PAGE = [
  {
    path: '*',
    component: () => import('@/components/404'),
  },
]

export const renderRoutes = () => {
  return new Promise((resolve) => {
    getMenus(getUserInfo()).then((res) => {
      const routesModules = res
      PAGE_HOME.redirect = (routesModules[0] && routesModules[0].path) || ''
      routesModules.unshift(PAGE_HOME) // 完成后加入 首页页面
      routesModules.push(...DEFAULT_PAGE) // 完成后加入 404页面
      // 页面首页地址重新赋值
      // 左侧菜单需要 routes 的数据渲染
      routesModules.forEach((it) => {
        if (!routes.some((route) => route.path === it.path)) {
          routes.push(it)
        }
      })
      addDynamicRoutes(ROUTER, routesModules)
      Vue.prototype.$nextTick(() => {
        setTimeout(resolve, 500)
      })
    })
  })
}

const ROUTER = new Router({
  mode: 'history',
  base: document.baseURI.replace(window.location.origin, ''),
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else if ((to.name == '队伍管理' || to.name == '作品管理' || to.name == '通知管理') && from.name == '首页') {
      return { x: 0, y: 0 }
    }
  },
  routes,
})

let isRenderRoutes = false
ROUTER.beforeEach(async (to, from, next) => {
  console.log('beforeEach')
  if (to.meta.title) {
    //如果设置标题，拦截后设置标题
    document.title = to.meta.title
  }
  if (
    navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i,
    )
  ) {
    if (to.path.indexOf('/Offcial') == -1) {
      next('/Offcial/H5notFound')
    }
  }
  /* 开发环境不做限制 */
  /* if (process.env.NODE_ENV === 'development') {
    next()
    return
  } */

  /* 
    是否登录
      登录了，不可以去 login
      没登陆，去的是 login，直接走
        不是，获取登录状态，获取到直接走，获取不到去 login    
    */
  const userInfo = getUserInfo()
  const isLogin = userInfo && userInfo.userId

  if (isLogin) {
    /* 跳转过来已经登录，第一次需要 */
    if (!isRenderRoutes) {
      renderRoutes()
    }
    if (to.path === '/login') {
      next(from.path)
    } else {
      next()
    }
    isRenderRoutes = true
  } else {
    if (to.path === '/login') {
      next()
      return
    }

    const res = await getLoginInfo()
    const outerData = res.data || {}
    const data = outerData.data
    if (!data) {
      next('/login')
    } else {
      handleUserInfo(data)
      renderRoutes().then(() => next('/'))
    }
  }
})

export default ROUTER
